package com.example.sunmiv1.dialog;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.sunmiv1.R;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class SetCreditMoneyDialog extends BaseDialog {

    @BindView(R.id.setCreditMoney_off)
    ImageView setCreditMoneyOff;
    @BindView(R.id.setCreditMoney_money)
    EditText setCreditMoneyMoney;
    @BindView(R.id.setCreditMoney_tip)
    TextView setCreditMoneyTip;
    @BindView(R.id.setCreditMoney_save)
    TextView setCreditMoneySave;
    @BindView(R.id.setCreditMoney_title)
    TextView setCreditMoneyTitle;
    JSONArray ids;
    private int type;
    private ACache aCache;
    private String creditMoney;

    private double maxMoney = 0, minMoney = 0;

    public static SetCreditMoneyDialog newInstance(JSONArray useId, int type) {
        SetCreditMoneyDialog fragment = new SetCreditMoneyDialog();
        Bundle bundle = new Bundle();
        bundle.putString("useId", useId.toString());
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_set_credit_money;
    }


    @Override
    protected void initData() {
        aCache = ACache.get(getContext());
        type = getArguments().getInt("type");
        try {
            ids = new JSONArray(getArguments().getString("useId"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        switch (type) {
            case 1:
                getQuota1();
                break;
            case 2:
                getQuota2();
                break;
            case 3:
                setCreditMoneyTitle.setText(R.string.setCreditMoneyTip1);
                setCreditMoneyMoney.setHint(R.string.setCreditMoneyTip2);
                try {
                    creditMoney = ids.getString(0);
                    setCreditMoneyTip.setText(getString(R.string.setCreditMoneyTip3) + creditMoney);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void initListener() {
        setCreditMoneyMoney.addTextChangedListener(new TextWatcher() { //在線支付
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String temp = setCreditMoneyMoney.getText().toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    setCreditMoneyMoney.setText(temp.substring(0,posDot+3));
                    setCreditMoneyMoney.setSelection(posDot+3);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            // 下面這些設置必須在此方法(onStart())中才有效
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0xff000000));
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            Window window = dialog.getWindow();
            // 如果不設置這句代碼, 那麼彈框就會與四邊都有一定的距離
            window.setBackgroundDrawableResource(android.R.color.transparent);
            window.setWindowAnimations(R.style.DialogFromBottom);// 設置動畫
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = dm.widthPixels;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.BOTTOM;
            window.setAttributes(setLayout(params));
        }
    }

    @OnClick({R.id.setCreditMoney_off, R.id.setCreditMoney_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setCreditMoney_off:
                dismiss();
                break;
            case R.id.setCreditMoney_save:
                String money = setCreditMoneyMoney.getText().toString().trim();
                if (type != 3) {
                    if (TextUtils.isEmpty(money)) {
                        Toast.makeText(getContext(), "請輸入要設置的額度", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(money) < 0) {
                        Toast.makeText(getContext(), "不能小於0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(money) < minMoney) {
                        Toast.makeText(getContext(), "不能小於最小額度", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(money) > maxMoney) {
                        Toast.makeText(getContext(), "不能大於最大額度", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(money)) {
                        Toast.makeText(getContext(), "請輸入還款金額", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(money) <= 0) {
                        Toast.makeText(getContext(), "請輸入大於0的還款金額", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(money) > Double.parseDouble(creditMoney)) {
                        Toast.makeText(getContext(), "還款金額不能大於待還金額", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                callback.success(money);
                dismiss();
                break;
        }
    }

    /**
     * 賒賬用戶單獨設置額度返回信息
     */
    private void getQuota1() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", ids.getJSONObject(0).getString("credit_id"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getContext(), Common.GET_USER_QUOTA1, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        JSONObject data = json.getJSONObject("data");
                        maxMoney = Double.parseDouble(data.getString("credit_quota"));
                        minMoney = Double.parseDouble(data.getString("total_arrearage"));
                        setCreditMoneyTip.setText(getString(R.string.setCreditMoneyTip4) + data.getString("quota") +
                                getString(R.string.setCreditMoneyTip5) + data.getString("total_arrearage") +
                                getString(R.string.setCreditMoneyTip6) + data.getString("credit_quota"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 賒銷批量設置額度返回信息
     */
    private void getQuota2() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("arr", ids);
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getContext(), Common.GET_USER_QUOTA2, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        JSONObject data = json.getJSONObject("data");
                        maxMoney = Double.parseDouble(data.getString("credit_quota"));
                        minMoney = Double.parseDouble(data.getString("arrearage"));
                        setCreditMoneyTip.setText(getString(R.string.setCreditMoneyTip7) + data.getString("arrearage") +
                                getString(R.string.setCreditMoneyTip8) + data.getString("credit_quota"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

}
